package org.example.platform.elasticsearch.service;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.example.platform.elasticsearch.entity.HotelDocRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsCreateDocService {
    @Autowired
    private RestHighLevelClient client;

    public Map<String, Object> singleIndexDoc(HashMap<String, Object> dataMap, String index, String id) throws IOException {
        IndexRequest indexRequest = new IndexRequest(index).id(id).source(dataMap);
        // 执行写入
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        String inde = indexResponse.getIndex();
        String ids = indexResponse.getId();
        long version = indexResponse.getVersion();
        HashMap<String,Object> map = new HashMap<>();
        map.put("index",inde);
        map.put("id",ids);
        map.put("version",version);
        return map;
    }

    public String bulkIndexDoc(HotelDocRequest hotelDocRequest) throws Exception {
       String indexName = hotelDocRequest.getIndexName();
       if(CharSequenceUtil.isBlank(indexName)){
           throw new Exception("索引名不能为空");
       }
        BulkRequest bulkRequest = new BulkRequest(indexName);
        List<Map<String,Object>> list = hotelDocRequest.getRecordMapList();
        for(Map<String,Object> dataMap: list){
            // 这个docIdKey代表map中值为docId对应的键值
            String docIdKey = hotelDocRequest.getDocIdKey();
            String docId = dataMap.get(docIdKey).toString();
            // 这里每次都使用new IndexRequest(index,type)，不然只会插入最后一条记录（这样插入不会覆盖已经存在的id，也就是不能更新）
            IndexRequest indexRequest = new IndexRequest().id(docId).source(dataMap);
            // 添加indexRequest
            bulkRequest.add(indexRequest);
        }
        // 设置超时时间
        bulkRequest.timeout(TimeValue.timeValueSeconds(6));
        BulkResponse bulkResponse;
       try{
           bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);
           if(bulkResponse.hasFailures()){
               return "失败，原因："+bulkResponse.buildFailureMessage();
           }else{
               return "成功";
           }
       }catch (Exception e){
           throw new Exception("搜索错误");
       }
    }
}
